package com.ll.common.core.common;

import com.ll.common.core.ex.BusinessException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;

@Component
public class JwtUtils {

    @Value("${token.expire}")
    private Integer expire;

    @Value("${token.secret}")
    private String secret;

    // 密钥
    // 令牌自定义标识
//    @Value("${token.header}")
//    private String header;

    public String createToken( HashMap<String, Object> map) {
        JwtBuilder jwtBuilder = Jwts.builder()
                // 签名和算法
                .signWith(SignatureAlgorithm.HS256, secret)
                // 过期时间(毫秒值)
                .setExpiration(new Date(System.currentTimeMillis() + expire * 60L * 1000L))
                // 自定义数据
                // .claim("username", "taotie")
                .addClaims(map);
        String token = jwtBuilder.compact();
        return token;
    }

    public Claims parseToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("令牌解析出错!");
        }
        return claims;
    }
    /**
     * 从请求头中获取令牌
     * @param request
     * @return
     */
//    public String getToken(HttpServletRequest request) {
//        String token = request.getHeader(header);
//        if (StringUtils.hasText(token)) {
//            return token;
//        }
//        return null;
//    }

}
